package com.cinema.api.config;

import com.cinema.api.auth.JwtAuthenticationEntryPoint;
import com.cinema.api.auth.JwtAuthorizationFilter;
import com.cinema.api.model.enums.ResultCodeEnum;
import com.cinema.api.model.result.Result;
import com.cinema.api.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;


/**
 * Security 配置类
 */
@Configuration
// 开启基于方法的安全认证机制 (配置true,方法上的@PreAuthorize()注解才会生效)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 定义白名单
     */
    public static final String[] URL_WHITELIST = {
            "/webjars/**",
            "/favicon.ico",
            "/api/user/register",
            "/api/cp/**",
            "/api/user/reset",
            "/api/user/login",
            "/api/admin/login",
            "/api/worker/login",
            "/api/upload",
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/swagger/**",
            "/v2/api-docs",
            "**/logout"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()// 开启跨域
                .headers().frameOptions().disable()// 允许跨域使用iframe
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()// 设置白名单
                .anyRequest().authenticated()// 要求所有接口都必须进行权限认证
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)// 禁用session
                .and()
                // .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)// 添加登录验证码过滤器在登录过滤器之前
                //.addFilterBefore(httpServletRequestReplacedFilter, Filter.class)
                .addFilter(new JwtAuthorizationFilter(authenticationManagerBean()))// 添加Jwt token过滤器

        ;
    }

    /**
     * 增加配置，让CORS正常工作
     * 由于SpringSecurity有默认的跨域配置，会无法放行请求头带有“Authorization”的请求
     * 防止前端请求API报cors error(401)错误
     */
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 添加配置
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedHeader("DELETE");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    /**
     * 注入BCryptPasswordEncoder
     * 密码加密方式
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
